using Microsoft.EntityFrameworkCore.Storage;
using UniversalAdminSystem.Application.Common.Interfaces;
using UniversalAdminSystem.Infrastructure.Persistence.DbContexts;

namespace UniversalAdminSystem.Infrastructure.Persistence.Transaction;

public class UnitOfWork : IUnitOfWork
{
    private readonly UniversalAdminSystemDbContext _context;
    private IDbContextTransaction _transaction;

    public UnitOfWork(UniversalAdminSystemDbContext context)
    {
        _context = context;
    }
    public async Task BeginTransactionAsync()
    {
        _transaction = await _context.Database.BeginTransactionAsync();
    }

    public async Task CommitAsync()
    {
        await _context.SaveChangesAsync();
        await _transaction.CommitAsync();
    }

    public async Task RollbackAsync()
    {
        if (_transaction != null)
        {
            await _transaction.RollbackAsync();
            _transaction = null;
        }
    }

    public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        return await _context.SaveChangesAsync(cancellationToken);
    }
}